package com.damai.action.json;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.citywithincity.api.entities.Customer;
import com.citywithincity.api.utils.ApiUtil;
import com.citywithincity.cache.CacheUtil;
import com.damai.action.NoAccessTokenError;
import com.damai.action.NotLoginError;

class TokenGetJson implements IGetJson {
	private IGetJson getJson;
	private boolean checkLogin;
	public TokenGetJson(IGetJson getJson,boolean checkLogin) {
		this.getJson = getJson;
		this.checkLogin = checkLogin;
	}
	
	@Override
	public Map<String, Object> getJson(HttpServletRequest request) throws IOException {
		String token = request.getHeader("token");
		if(token == null){
			throw new NoAccessTokenError();
		}
		if(token.isEmpty()){
			throw new NoAccessTokenError();
		}
		Customer customer = CacheUtil.get(token);
		if(customer==null){
			throw new NoAccessTokenError();
		}
		final boolean checkLogin =this.checkLogin;
		if(checkLogin && customer.getId() == null){
			throw new NotLoginError();
		}
		
		final IGetJson getJson = this.getJson;
		request.setAttribute("customer", customer);
		
		Map<String, Object> json = getJson.getJson(request);
		/*
		if (!SignUtil.verify(json, customer.getKey())) {
			throw new SignError();
		}*/
		request.setAttribute("time", json.get(ApiUtil.time));
		json.put("customer", customer);
		return json;
	}

}
